﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Globalization;
using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.Collections.Generic;

namespace DongDong.Common
{
    /// <summary>
    /// Summary description for Misc
    /// </summary>
    public partial class Misc
    {


        public Misc()
        {

        }

        public static string GetMonth(int month)
        {
            if (month == 1)
                return "一月";
            else if (month == 2)
                return "二月";
            else if (month == 3)
                return "三月";
            else if (month == 4)
                return "四月";
            else if (month == 5)
                return "五月";
            else if (month == 6)
                return "六月";
            else if (month == 7)
                return "七月";
            else if (month == 8)
                return "八月";
            else if (month == 9)
                return "九月";
            else if (month == 10)
                return "十月";
            else if (month == 11)
                return "十一月";
            else
                return "十二月";
        }

        //查询html中的代码获取第一个图片地址并且图片地址路径中不包含NonePath 如果没有则返回NoneImgSrc
        public static string GetImgUrl(object HTMLStr, string NoneImgSrc)
        {

            string str = string.Empty;
            Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>", RegexOptions.Compiled);
            Match m = r.Match(HTMLStr.ToString().ToLower());
            if (m.Success)
            {
                str = m.Result("${url}").Replace('\"', ' ').Trim();
            }
            else
            {
                str = "NoneImgSrc"; //否则显示默认图片
            }
            return str;
        }


        public static DateTime GetMondayDate(DateTime startDate)
        {
            DateTime returnDate;

            if (startDate.DayOfWeek == DayOfWeek.Monday)
                returnDate = startDate;
            else
                returnDate = GetMondayDate(startDate.AddDays(-1));

            return returnDate;
        }

        public static DateTime GetNextSundayDate(DateTime startDate)
        {
            DateTime returnDate;

            if (startDate.DayOfWeek == DayOfWeek.Sunday)
                returnDate = startDate;
            else
                returnDate = GetNextSundayDate(startDate.AddDays(1));

            return returnDate;
        }

        public static string ReplaceLineReturns(object text)
        {
            string returnText = text.ToString();
            string breakChar = ((char)13).ToString();

            return returnText.Replace(breakChar, "<br />").Replace("<br /><br /><br />", "<br />").Replace("<br /><br />", "<br />");
        }

        public static string ClearHtml(object text)
        {
            if (text != null)
                return ClearHtml(text.ToString());
            else
                return "";

        }

        public static string ClearHtml(string text)
        {
            string Pattern = "(<[^>]*>)";

            text = text.Replace("&nbsp;", " ");
            text = text.Replace("&quot;", "");
            text = Regex.Replace(text, Pattern, "");
            Pattern = "[<]";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[>]";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[--]";

            text = Regex.Replace(text, "'", "''");
            text = Regex.Replace(text, ";", "");
            text = Regex.Replace(text, "\"", "");

            return text;

        }

        //public static string GetRRP(object rrp)
        //{
        //    UserAccount curUSer = UserAccount.GetCurrent();

        //    decimal rrpPrice = DongDong.Common.Misc.ConvertToDecimal(rrp.ToString());

        //    if (rrpPrice > 0)
        //        return "RRP: " + rrpPrice.ToActiveCurrency();
        //    else
        //        return "";
        //}

        //public static string GetRRP(object rrp, object offerCost, object cost)
        //{
        //    UserAccount curUSer = UserAccount.GetCurrent();

        //    decimal rrpPrice = DongDong.Common.Misc.ConvertToDecimal(rrp.ToString());
        //    decimal offerPrice = DongDong.Common.Misc.ConvertToDecimal(offerCost.ToString());
        //    decimal sellPrice = DongDong.Common.Misc.ConvertToDecimal(cost.ToString());

        //    if (rrpPrice > 0)
        //        return "RRP: " + rrpPrice.ToActiveCurrency();
        //    else if (offerPrice > 0 && sellPrice != 0m)
        //        return "WAS:" + cost.ToActiveCurrency();
        //    else
        //        return "";
        //}

        public static DateTime? ConvertToDateTime(string date, DateTime? returnValue)
        {
            DateTime? newValue = returnValue;

            try
            {
                newValue = Convert.ToDateTime(date);
            }
            catch
            {
            }

            return newValue;
        }

        public static DateTime ConvertToDateTime(string date)
        {
            DateTime newValue = DateTime.Now;

            try
            {
                newValue = Convert.ToDateTime(date);
            }
            catch
            {
            }

            return newValue;
        }

        public static string ConvertToShortDateTime(object date, string format)
        {
            string newValue = "";

            try
            {
                if (date != null)
                    newValue = Convert.ToDateTime(date).ToString(format);
            }
            catch
            {
            }

            return newValue;
        }

        public static string AddBRs(string input)
        {
            char retChar = (char)13;
            input = input.Replace(retChar.ToString(), "<br />");
            return input;
        }

        public static string GetMonthName(int monthID)
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();

            return info.GetMonthName(monthID);
        }

        //public static string ClearForFileName(string str)
        //{
        //    string filename = str;

        //    filename = filename.Replace(" ", "");

        //    return filename;
        //}

        //public static string ReplaceAmpersands(object amp)
        //{
        //    string ampersand = amp.ToString();

        //    ampersand = ampersand.Replace("&", "&amp;");

        //    return ampersand;
        //}
        public static string ClearFilename(object filename)
        {
            string file = "";
            if (filename != null)
            {
                file = Convert.ToString(filename);

                file = file.Replace("&", "");
                file = file.Replace("|", "");
                file = file.Replace("'", "");
                file = file.Replace("\"", "");
                file = file.Replace("%", "");
                file = file.Replace("?", "");
                file = file.Replace("@", "");
                file = file.Replace("/", "");
                file = file.Replace(":", "");
                file = file.Replace(".", "");
                file = file.Replace("-", "");
                file = file.Replace("*", "");
                file = file.Replace("\\", "");
                file = file.Replace(" ", "_");
            }

            return file;
        }

        public static string ClearCharacters(string filename)
        {
            string file = Convert.ToString(filename);

            file = file.Replace("%20", "[space]");
            file = file.Replace("&", "");
            file = file.Replace("|", "");
            file = file.Replace("'", "");
            file = file.Replace("\"", "");
            file = file.Replace("%", "");
            file = file.Replace("?", "");
            file = file.Replace("@", "");
            file = file.Replace("//", "");
            file = file.Replace(">", "");

            return file;
        }


        //public static string ClearTags(object text)
        //{
        //    // To Validate Website
        //    // chars of the form ' kill validation
        //    string information = "";
        //    if (text != null)
        //    {
        //        information = text.ToString();
        //        information = information.Replace("'", "");
        //        information = information.Replace("&", "and");
        //    }


        //    return information;
        //}

        public static string GetFilename(string name, string extension)
        {
            string filename = name;

            filename = filename.Replace(" ", "");
            filename = filename.Replace(extension, "");

            filename = filename + "-" + DateTime.Now.ToString("ddMMyyhhmm");
            filename = filename + extension;

            return filename;
        }

        public static string[] SplitString(string text, char delimiter)
        {
            string[] items = text.Split(delimiter);
            return items;
        }

        public static string CapitaliseFirstLetter(string text)
        {
            try
            {
                if (text.Length > 0)
                {
                    text = text[0].ToString().ToUpper() + text.Substring(1);
                }
            }
            catch { }

            return text;
        }

        public static string LowerFirstLetter(string text)
        {
            if (text.Length > 0)
            {
                text = text[0].ToString().ToLower() + text.Substring(1);
            }

            return text;
        }

        public static void WriteToFile(string strPath, ref byte[] Buffer)
        {
            // Create a file
            FileStream newFile = new FileStream(strPath, FileMode.Create);

            // Write data to the file
            newFile.Write(Buffer, 0, Buffer.Length);

            // Close file
            newFile.Close();
        }

        public static string GetPageHTML(string URL)
        {
            try
            {

                System.Net.WebClient webClient = new System.Net.WebClient();
                string strUrl = URL;
                byte[] reqHTML;

                reqHTML = webClient.DownloadData(strUrl);

                return System.Text.Encoding.UTF8.GetString(reqHTML);
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        public static string NewGUID()
        {
            string newGUID;

            newGUID = Guid.NewGuid().ToString();

            return newGUID;
        }

        public static string BoolToYesNo(object boolString)
        {
            try
            {
                bool value = Convert.ToBoolean(boolString);
                if (value)
                    return "是";
                else
                    return "否";
            }
            catch
            {
                return "否";
            }
        }
        public static int BoolToInt(bool value)
        {
            if (value == true)
                return 1;
            else
                return 0;
        }


        public static bool IntToBool(int value)
        {
            if (value == 1)
                return true;
            else
                return false;
        }

        public static bool IsDecimal(string value)
        {
            decimal newValue = 0;
            value = value.Replace("£", "").Replace("￥", "");

            if (Decimal.TryParse(value, out newValue) == true)
                return true;
            else
                return false;
        }

        public static decimal ConvertToDecimal(string value)
        {
            decimal newValue = 0;
            value = value.Replace("£", "").Replace("￥", "");

            Decimal.TryParse(value, out newValue);

            return newValue;
        }

        public static decimal ConvertToDecimal(double value)
        {
            decimal newValue = 0;

            Decimal.TryParse(value.ToString(), out newValue);

            return newValue;
        }

        public static double ConvertToDouble(string value)
        {
            double newValue = 0;

            Double.TryParse(value.ToString(), out newValue);

            return newValue;
        }

        public static int ConvertToInt(object value)
        {
            int newValue = 0;
            try
            {
                newValue = Convert.ToInt32(value);
            }
            catch { }

            return newValue;
        }

        public static int ConvertToInt(string value)
        {
            int newValue = 0;

            Int32.TryParse(value, out newValue);

            return newValue;
        }

        static public string StripHTML(string text)
        {
            string Pattern = "(<[^>]*>)";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[<]";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[>]";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[--]";

            text = Regex.Replace(text, "'", "''");
            text = Regex.Replace(text, ";", "");
            text = Regex.Replace(text, "\"", "");

            return text;
        }

        //取出html里面的字符和回车以及换行
        static public string StripHTMLAndReturnLines(string text)
        {
            string Pattern = "(<[^>]*>)";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[<]";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[>]";

            text = Regex.Replace(text, Pattern, "");
            Pattern = "[--]";

            text = Regex.Replace(text, "'", "''");
            text = Regex.Replace(text, ";", "");
            text = Regex.Replace(text, "\"", "");
            text = Regex.Replace(text, ((char)13).ToString(), "");
            text = Regex.Replace(text, ((char)10).ToString(), "");

            return text;
        }

        //去除脚本
        static public string ReplaceStript(string text)
        {
            string Pattern = "<script[^>]*?>.*?</script>";
            text = Regex.Replace(text, Pattern, "", RegexOptions.IgnoreCase);
            return text;
        }

        public static string GetFormValue(string param)
        {
            string value = string.Empty;

            try
            {
                value = HttpContext.Current.Request.Form[param].ToString();
            }
            catch
            {
            }

            return value;
        }

        public static int GetFormValueAsInt(string param)
        {
            int value = 0;

            try
            {
                value = Convert.ToInt32(HttpContext.Current.Request.Form[param]);
            }
            catch
            {
            }

            return value;
        }

        /// <summary>
        /// Returns a integer value from the querystring data, will return 0 if not found
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static int GetQueryStringAsInt(string param)
        {
            int value = 0;

            try
            {
                if (HttpContext.Current.Request.QueryString[param] != null)
                    value = Convert.ToInt32(HttpContext.Current.Request.QueryString[param].ToString());
            }
            catch
            {
            }

            return value;
        }


        public static string GetQueryString(string param)
        {
            string value = string.Empty;

            try
            {
                value = HttpContext.Current.Request.QueryString[param].ToString().Replace(" ", "");
            }
            catch
            {
            }

            return value;
        }

        public static string GetQueryString(string param, string defaultValue)
        {
            string value = string.Empty;

            try
            {
                value = HttpContext.Current.Request.QueryString[param].ToString();
            }
            catch
            {
                value = defaultValue;
            }

            return value;
        }

        static public bool FutureDate(string sdate)
        {
            DateTime dt;
            bool isDate = true;

            try
            {
                dt = DateTime.Parse(sdate);

                if (dt > DateTime.Now)
                    isDate = false;
            }
            catch
            {
                isDate = false;
            }

            return isDate;
        }

        /// <summary>
        /// Returns true only at 0,5,10,15,20,25,30,35,40,45,50,55 minutes past the hour
        /// </summary>
        /// <returns></returns>
        public static bool IsMinuteByFive()
        {
            bool valid = false;
            int number = 0;

            try
            {
                number = Int32.Parse(((Convert.ToDouble(DateTime.Now.Minute + 5) / Convert.ToDouble(5)).ToString()));

                if (number >= 0)
                    valid = true;
            }
            catch
            {
            }

            return valid;
        }

        static public void SetMetaValues(System.Web.UI.HtmlControls.HtmlHead head, string name, string content)
        {
            HtmlMeta metaValue = null;

            metaValue = new HtmlMeta();
            metaValue.Attributes.Add("name", name);
            metaValue.Attributes.Add("content", content);
            head.Controls.Add(metaValue);
        }

        public static string MaxCharacters(string text, int characters)
        {
            string value = text;

            if (value.Length > characters)
                value = value.Substring(0, characters);

            return value;
        }


        //将list<string>用speater拼接成string
        public static string GetArrayStr(List<string> list, string speater)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sb.Append(list[i]);
                }
                else
                {
                    sb.Append(list[i]);
                    sb.Append(speater);
                }
            }
            return sb.ToString();
        }

        public static List<string> GetSubStringList(string o_str, char sepeater)
        {
            List<string> list = new List<string>();
            string[] ss = o_str.Split(sepeater);
            foreach (string s in ss)
            {
                if (!string.IsNullOrEmpty(s) && s != sepeater.ToString())
                {
                    list.Add(s);
                }
            }
            return list;
        }


        public static string MaxCharacters(object text, int characters)
        {
            if (text != null)
            {
                string value = text.ToString();

                if (value.Length > characters)
                    value = value.Substring(0, characters);


                return value;
            }
            else
            {
                return "";
            }
        }

        public static string MaxCharacters(object text, int characters, string append)
        {
            if (text != null)
            {
                string value = text.ToString();

                if (value.Length > characters)
                    value = value.Substring(0, characters) + append;

                return value;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Upload file
        /// </summary>
        /// <param name="fileUploadControl">Upload Control</param>
        /// <param name="uploadPath">Relative path to save file to, with trailing /</param>
        /// <param name="allowedExtensions">exensions allowed, lowercase (.jpg .gif)</param>
        /// <returns>Filename is returned, without the path</returns>
        public static string UploadFile(FileUpload fileUploadControl, string uploadPath, string allowedExtensions)
        {
            string savePath = HttpContext.Current.Server.MapPath(uploadPath);
            string newFileName = "";

            if (fileUploadControl.HasFile)
            {
                string fileName = DongDong.Common.Misc.MaxCharacters(HttpContext.Current.Server.HtmlEncode(fileUploadControl.FileName), 30).ToLower();
                string extension = System.IO.Path.GetExtension(fileName).ToLower();

                if (allowedExtensions.Contains(extension))
                {
                    newFileName = DongDong.Common.Misc.MaxCharacters(System.Guid.NewGuid().ToString(), 5) + "-" + fileName.Replace(extension, "") + extension;

                    savePath += newFileName;
                    fileUploadControl.SaveAs(savePath);
                }
                else
                {
                    newFileName = "";
                }
            }

            return newFileName;
        }

        /// <summary>
        /// Finds a value from a custom querystring data, this doesn't use the page form data
        /// </summary>
        /// <param name="text">Text containing querystring data</param>
        /// <param name="param">Param to find</param>
        /// <returns></returns>
        public static string FindValueFromQueryString(string text, string param)
        {
            try
            {
                string[] SplitStrings = text.Split("&".ToCharArray());

                foreach (string Split in SplitStrings)
                {
                    string[] SplitAgain = Split.Split("=".ToCharArray());

                    try
                    {
                        if (SplitAgain[0].ToLower() == param.ToLower())
                        {
                            return SplitAgain[1];
                        }
                    }
                    catch
                    {
                    }

                    SplitAgain = null;
                }

                SplitStrings = null;
            }
            catch
            {
                return "";
            }

            return "";
        }

        public static void Serialize<T>(T xmlObject, string pathName, Encoding encoding)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(HttpContext.Current.Server.MapPath(pathName), encoding);
            xmlTextWriter.WriteStartDocument();
            xmlTextWriter.Formatting = Formatting.Indented;
            xmlSerializer.Serialize(xmlTextWriter, xmlObject);
            xmlTextWriter.WriteEndDocument();
            xmlTextWriter.Close();
        }
        public static string GetPassword()
        {
            string allchars = "0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ ";
            StringBuilder res = new StringBuilder(6);
            Random rand = new Random();

            for (int i = 0; i < 4; i++)
            {
                res.Append(allchars[rand.Next(10)]);
            }

            for (int i = 0; i < 2; i++)
            {
                res.Append(allchars[rand.Next(10, allchars.Length)]);
            }
            return res.ToString();
        }


        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToSBC(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        ///  转半角的函数(SBC case)
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }
    }
}